package com.bitmain.test.detectortest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;

import com.bitmain.ulnar.aider.JSONAider;
import com.bitmain.ulnar.aider.http.HTTPClientSide;
import com.bitmain.ulnar.aider.http.HTTPRequestMessage;
import com.bitmain.ulnar.aider.http.HTTPResponseMessage;

/**
 * 
 *
 * @author Richard - rui.wu@bitmain.com
 * @since 2016年8月8日 
 *
 */
public class MinerUtils  {
	private static final String MINER_HTTP_USERNAME = "root"; 
	private static final String MINER_HTTP_PASSWORD = "root"; 
	
	public static Boolean pingMiner(String host){
		boolean reachable = false;
		
		try {
			reachable = InetAddress.getByName(host).isReachable(3000);
		} catch (Exception e) {
			System.out.println("ping 失败");
		}
		return reachable;
	}
	
	public static String getMinerMac(String ip){
		String mac = null;
		String content = null;
		try {
			String url = "http://" + ip + "/cgi-bin/get_network_info.cgi";
			
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(new AuthScope(ip, 80), new UsernamePasswordCredentials(MINER_HTTP_USERNAME, MINER_HTTP_PASSWORD));
			HttpClientContext context = new HttpClientContext();
	        context.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider);
	        
	        HTTPRequestMessage request = new HTTPRequestMessage();
	        request.setUrl(url);
	        HTTPResponseMessage response = HTTPClientSide.get(request, context, 3000);
	        content = response.getContent();
	        if (StringUtils.isNotBlank(content)) {
	        	mac = JSONAider.getString(content, "macaddr");
	        }
		} catch (Exception e) {
//			if (StringUtils.isNotBlank(content)) {
//				content = content.replace("\r\n", "");
//			}
//			logger.error("getMinerMAC error - content : " + content);
		}
		return mac;
	}
	
	public static enum Command {
		/**
		 * 矿机MAC地址命令
		 */
		MAC("", 1 << 1),
		/**
		 * 矿机状态信息命令
		 */
		STATS("{\"command\":\"stats\"}", 1 << 2),
		/**
		 * 矿机汇总信息命令
		 */
		SUMMARY("{\"command\":\"summary\"}", 1 << 3),
		/**
		 * 矿机矿池配置信息命令
		 */
		POOLS("{\"command\":\"pools\"}", 1 << 4),
		/**
		 * 所有命令
		 */
		ALL("", 1 << 5);
		
		public int key;
		public String value;
		
		private Command(String value, int key) {
			this.value = value;
			this.key = key;
		}
	}
	
	public static String request(String host, int port, String cmd){

		Socket socket = null;
		BufferedWriter writer = null;
		BufferedReader reader = null;
		StringBuilder response = new StringBuilder();
		System.out.println(cmd);
		
		try {
			socket = new Socket();
			socket.setSoTimeout(20000);
			socket.connect(new InetSocketAddress(host,port));
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			writer.write(cmd);
			writer.flush();
			
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String line;
			while((line=reader.readLine())!=null){
				response.append(line);
			}
			
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
				if (writer != null) {
					writer.close();
				}
				if (socket != null) {
					socket.close();
				}
				
			} catch (Exception e2) {
			}
		}
		return response.toString().trim();
	}
	
	public static void main(String[] args) {
		String host = "192.168.20.45";
		int port = 4028;
		String cmd = Command.STATS.value;
		
		System.out.println(pingMiner(host));
		System.out.println(getMinerMac(host));
		System.out.println(request(host, port, cmd));
	}
}
